<template>
  <div>
    <a-card :bordered='false'>
      <!--  #####################查询条件###################  -->
      <div class='table-page-search-wrapper'>
        <a-form layout='inline'>
          <a-row :gutter='48'>
            <a-col :md='8' :sm='24'>
              <a-form-item label='订单类型'>
                <a-select placeholder='订单类型' v-model='queryParam.type' allowClear>
                  <a-select-option :value="parseInt(1)">优惠券订单</a-select-option>
                  <a-select-option :value="parseInt(2)">权益包订单</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md='8' :sm='24'>
              <a-form-item label='商户订单号'>
                <a-input placeholder='商户订单号' v-model='queryParam.outTradeNo' allowClear />
              </a-form-item>
            </a-col>
            <a-col :md='8' :sm='24'>
              <a-form-item label='交易订单号'>
                <a-input placeholder='交易订单号' v-model='queryParam.transactionId' allowClear />
              </a-form-item>
            </a-col>
            <a-col :md='8' :sm='24'>
              <a-form-item label='付款状态'>
                <a-select placeholder='付款状态' v-model='queryParam.status' allowClear>
                  <a-select-option value='0'>未支付</a-select-option>
                  <a-select-option value='1'>已付款</a-select-option>
                  <a-select-option value='3'>已退款</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md='8' :sm='24'>
              <a-form-item label='开始时间'>
                <a-date-picker placeholder='开始时间' format='YYYY-MM-DD' v-model='queryParam.beginTime'
                               style='width: 100%' />
              </a-form-item>
            </a-col>
            <a-col :md='8' :sm='24'>
              <a-form-item label='结束时间'>
                <a-date-picker placeholder='结束时间' format='YYYY-MM-DD' v-model='queryParam.endTime'
                               style='width: 100%' />
              </a-form-item>
            </a-col>
            <a-col :md='!advanced && 8 || 24' :sm='24' style='margin-bottom: 10px'>
              <a-button v-action:query type='primary' @click='$refs.table.refresh(true)'>查询</a-button>
              <a-button style='margin-left: 8px' @click='reset()'>重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class='table-operator'>
        <a-button type='primary' :loading='loading' @click='exportExcell()'>导出EXCEL</a-button>
      </div>

      <!--  #####################操作###################  -->
      <div class='table-operator'>
        <!--<span>订单总数：<a-tag color="blue">{{statistics.ordercount}}</a-tag></span>-->
        <span>总金额：<a-tag color='cyan'>￥{{ statistics.orderAmount }}元</a-tag></span>
        <!--<span>已付订单：<a-tag color="green">{{statistics.paycount}}</a-tag></span>-->
        <span>已付金额：<a-tag color='green'>￥{{ statistics.payAmount }}元</a-tag></span>
        <!--<span>未付订单：<a-tag color="#f50">{{statistics.uncount}}</a-tag></span>-->
        <span>待付金额：<a-tag color='pink'>￥{{ statistics.waitAmount }}元</a-tag></span>
        <span>失效金额：<a-tag color='pink'>￥{{ statistics.unpayAmount }}元</a-tag></span>
        <span>退款金额：<a-tag color='pink'>￥{{ statistics.refundAmount }}元</a-tag></span>
        <!--        <span>支付率：<a-tag color="purple">{{successRate}}%</a-tag></span>-->
      </div>
      <!--  #####################表格###################  -->
      <s-table ref='table' :columns='columns' :data='loadData'>
        <a-tag slot='status' slot-scope='text' :color='text | statusColorFilter'>
          {{ text | statusFilter }}
        </a-tag>
        <a-tag slot='notityStatus' slot-scope='text, record' :color='text | notityColorFilter'>
          {{ text | notityFilter }}
        </a-tag>
        <a-tag slot='profitStatus' slot-scope='text, record' :color='text | profitColorFilter'>
          {{ text | profitStatusFilter }}
        </a-tag>
        <span v-action:other slot='useableAmount' slot-scope='text, record'>
          <div>{{ text }}元</div>
        </span>
        <span v-action:other slot='profitAmount' slot-scope='text, record'>
          <div>{{ text }}元</div>
        </span>
        <span slot='name' slot-scope='text, record'>
          <div>{{ text == null ? record.merchantName : text }}</div>
        </span>
        <span slot='action' slot-scope='text, record'>
          <template>
<!--            <a v-action:query v-if="record.notifyStatus==2" @click="doNotice(record)">重新通知</a>-->
            <!--            <a-divider v-action:query v-if="record.notifyStatus==2" type="vertical" />-->
            <!--            <a v-action:other v-if="record.status!=1" @click="handleBudan(record)">补单</a>-->
            <!--            <a-divider v-action:other v-if="record.notifyStatus==2" type="vertical" />-->
            <!--            <a v-action:other v-if="record.status==1 && record.profitStatus==4" @click="handleDel(record)">解冻分账</a>-->
            <a v-action:other v-if='record.status == 1 && record.type==1' @click='refund(record)'>退款</a>
          </template>
        </span>
      </s-table>

      <!--  #####################打开的页面###################  -->
      <user-edit ref='createModal' @ok='refresh' />

    </a-card>
  </div>
</template>

<script>
import { STable } from '@/components'
import userEdit from './budan'
import { selectAllAccount } from '@/api/shop/account'
import { selectPage, doNotice, doBudan, beginProfit, endProfit, refund, exportExcel } from '@/api/shop/trade'

/**
 * 组件
 */
const components = { STable, userEdit }

const columns = [
  {
    title: '商品名称',
    dataIndex: 'productName'
  },
  {
    title: '订单金额',
    dataIndex: 'amount',
    customRender: (text) => text + ' 元'
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '支付时间',
    dataIndex: 'payTime',
    ellipsis: true,
    width: 200
  },
  {
    title: '客户订单号',
    dataIndex: 'outTradeNo'
  },
  {
    title: '交易订单号',
    dataIndex: 'transactionId',
    ellipsis: true
  },
  {
    title: '用户昵称',
    dataIndex: 'nickName',
    ellipsis: true
  },
  {
    title: '用户电话',
    dataIndex: 'mobile',
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '100px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    status: '',
    text: '未支付'
  },
  1: {
    status: 'cyan',
    text: '已支付'
  },
  2: {
    status: 'red',
    text: '已失效'
  },
  3: {
    status: 'red',
    text: '已退款'
  }
}
const profitStatusMap = {
  0: {
    status: '',
    text: '不分账'
  },
  1: {
    status: '#80ff78',
    text: '未分账'
  },
  2: {
    status: '#4f4fff',
    text: '已分账'
  },
  3: {
    status: '#ffa4e6',
    text: '解冻分账'
  },
  4: {
    status: '#ff2d32',
    text: '分账失败'
  }
}
const notityMap = {
  0: {
    status: '',
    text: '未通知'
  },
  1: {
    status: '#2db7f5',
    text: '已通知'
  },
  2: {
    status: '#f50',
    text: '通知失败'
  }
}

/**
 * 数据
 */
const data = function() {
  return {
    // 高级搜索 展开/关闭
    advanced: false,
    // 查询参数
    queryParam: {
      memberId: null,
      type:1
    },
    columns,
    loading: false,
    merchants: [],
    accounts: [],
    customers: [],
    passageways: [],
    //统计信息
    successRate: 0,
    statistics: {
      orderCount: 0,
      orderAmount: 0,
      payCount: 0,
      payAmount: 0,
      unpayCount: 0,
      unpayAmount: 0,//失效金额
      waitAmount: 0,//未支付金额
      refundAmount: 0//退款金额
    },
    // 加载数据方法 必须为 Promise 对象
    loadData: parameter => {
      return selectPage(Object.assign(parameter, this.queryParam)).then(res => {
        this.statistics = res.data.statistics
        this.successRate = Math.round((parseFloat((this.statistics.payCount) / this.statistics.orderCount).toFixed(2) * 100))
        return res.data.pageInfo
      })
    }
  }
}

const created = function() {
  this.queryParam.memberId = this.$route.query.memberId
}

/**
 * 过滤器
 */
const filters = {
  statusFilter(status) {
    return statusMap[status].text
  },
  statusColorFilter(status) {
    return statusMap[status].status
  },
  notityFilter(status) {
    return notityMap[status].text
  },
  notityColorFilter(status) {
    return notityMap[status].status
  },
  profitStatusFilter(status) {
    return profitStatusMap[status].text
  },
  profitColorFilter(status) {
    return profitStatusMap[status].status
  }
}

/**
 * 计算属性
 */
const computed = {}

/**
 * 侦听器
 */
const watch = {}

export default {
  data: data,
  components: components,
  created: created,
  filters: filters,
  computed: computed,
  watch: watch,
  /**
   * 方法
   */
  methods: {
    handleAdd() {
      this.$refs.createModal.add()
    },
    handleEdit(record) {
      this.$refs.createModal.edit(record)
    },
    refresh() {
      this.$refs.table.refresh()
    },
    handleDel(record) {
      const _this = this
      this.$confirm({
        title: '警告',
        content: `可以先尝试再次分账，如果不行就解冻次订单`,
        okText: '解冻',
        okType: 'danger',
        cancelText: '再次分账',
        onOk() {
          // 在这里调用删除接口
          endProfit(record.id).then(res => {
            _this.$refs.table.refresh()
          })
        },
        onCancel() {
          beginProfit(record.id).then(res => {
            _this.$refs.table.refresh()
          })
        }
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    //展开
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    //联动选择
    handleSelect(value) {
      if (value) {
        selectAllAccount({ merchantCode: value }).then(res => {
          if (res.code === 200) {
            this.accounts = res.result
          }
        })
      }
    },
    //补单
    handleBudan(record) {
      // this.$refs.createModal.edit(record)
      doBudan({ outTradeNo: record.outTradeNo }).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        }
      })
    },
    //从新通知
    doNotice(record) {
      doNotice({ outTradeNo: record.outTradeNo }).then(res => {
        if (res.code === 200) {
          this.$message.info(res.message)
          this.$refs.table.refresh()
        }
      })
    },
    refund(record) {
      const _this = this
      this.$confirm({
        title: '警告',
        content: `确认退款?`,
        okText: '退款',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          refund(record.id).then(res => {
            if (res.code == 200) {
              _this.$message.info('退款成功')
              _this.$refs.table.refresh()
            }
          })
        }
      })

    },
    exportExcell() {
      this.loading = true
      exportExcel(this.queryParam).then(res => {
        this.loading = false
        const link = document.createElement('a')
        let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', '订单列表.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    },
    reset(){
      this.queryParam = {
        type : 1
      }
    }
  }
}
</script>
